package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderItemConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.service.PayOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author gatsby
 * @since 2022/10/30 16:21
 */
public class PayOrderServiceImpl implements PayOrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    StockMapper stockMapper;

    /**
     * 订单支付成功后修改订单的业务逻辑
     *
     * @param orderId
     * @return void
     * @author gatsby
     * @since 2022/10/30 16:38
     */
    @Override
    public void payOrderSuccess(String orderId) {
        //修改订单的状态为已支付
        int rows = orderMapper.updateStatusToPayedByOrder(orderId);
        if (rows != 1) {
            throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
        }
        //根据订单查询对应的商品信息
        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
        for (OrderItem orderItem : orderItems) {
            //更新对应的库存
            Stock stock = new Stock();
            stock.setLockCount(-orderItem.getNum());
            stock.setStockCount(Long.valueOf(0));
            stock.setItemId(orderItem.getItemId());
            stockMapper.updateStock(stock);
        }
        //根据订单id修改对应的库存状态
        orderItemMapper.updateStockStatus(OrderItemConstants.ORDER_ITEM_STATUS_REDUCE_SUCCESS,orderId);
    }
}
